package com.tg.app.activity.device.settings;

import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.TextView;

import com.appbase.custom.constant.CommonConstants;
import com.appbase.custom.constant.DeviceStateConstants;
import com.demo.view.SettingItemSwitchView;
import com.tange.base.toolkit.TGThreadPool;
import com.tange.module.camera.hub.CameraHub;
import com.tange.module.device.feature.DeviceFeature;
import com.tange.module.device.feature.DeviceFeatureObjectBox;
import com.tg.app.R;
import com.tg.app.activity.base.DeviceSettingsBaseActivity;
import com.tg.app.activity.device.DeviceSettingHelper;
import com.tg.app.activity.device.DeviceSettingsActivity;
import com.tg.app.camera.AVIOCTRLDEFs;
import com.tg.app.camera.Camera;
import com.tg.app.helper.DeviceFeatureHelper;
import com.tg.app.helper.DeviceHelper;
import com.tg.app.helper.SpeakerVolumeHelper;
import com.tg.appcommon.android.Packet;
import com.tg.appcommon.android.ResourcesUtil;
import com.tg.appcommon.android.TGLog;
import com.tg.data.bean.DeviceItem;
import com.tg.data.bean.DeviceSettingsInfo;
import com.tg.data.media.OnICameraListener;
import com.widget.OnRangeChangedListener;
import com.widget.RangeSeekBar;


public class SpeakerVolumeActivity extends DeviceSettingsBaseActivity implements OnICameraListener {
    private static final String TAG = "SpeakerVolumeActivity";
    private static final int TCI_CMD_SET_MIC_LEVEL_REQ = 0x043A;
    private static final int TCI_CMD_GET_MIC_LEVEL_REQ = 0x043C;

    private RangeSeekBar mVolumeSeekbar;
    private TextView mVolumeTextView;
    private DeviceSettingsInfo info;
    private Camera camera;
    private DeviceFeature deviceFeature;
    private SettingItemSwitchView mMicrophoneRL;
    private DeviceItem deviceItem;
    private RangeSeekBar mMicVolumeSeekbar;


    @Override
    protected void onSetupFailed() {

    }

    @Override
    public boolean shouldSetStatusBarColor() {
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_speaker_volume);
        hideActionBar();
        initData();
        initView();

        if (info != null){
            int progress =  adjustProgress(info.speakerVolume);
            mVolumeSeekbar.setProgress(progress);
            progress = progress / 10;
            String text = ResourcesUtil.getString(R.string.speaker) + " " + progress;
            mVolumeTextView.setText(text);
        }

        if (DeviceHelper.isLockBell(deviceItem)) {
            mMicrophoneRL.setVisibility(View.GONE);
            findViewById(R.id.ll_mic_volume_seekbar).setVisibility(View.GONE);
        }

        findViewById(R.id.ll_speaker_volume_seekbar).setVisibility(deviceFeature != null && deviceFeature.supportSpeakerTune? View.VISIBLE : View.GONE);

        if (deviceFeature != null && deviceFeature.supportSpeakerTune){
            camera.sendIOCtrl(AVIOCTRLDEFs.TCI_CMD_GET_VOLUME_REQ, new byte[1]);
        }

        if (DeviceFeatureHelper.isSupportMicrophoneSetting(deviceFeature)) {
            findViewById(R.id.ll_mic_volume_seekbar).setVisibility(View.VISIBLE);
            mMicrophoneRL.setVisibility(View.VISIBLE);
            mMicrophoneRL.setChecked(info.microphoneOn == DeviceStateConstants.DEVICE_OPEN);
            if (info.microphoneOn == DeviceStateConstants.DEVICE_OPEN){
                showMicSeekBar(deviceFeature.supportMicrophoneTune);
            }else{
                showMicSeekBar(false);
            }

            if (camera != null){
                camera.sendIOCtrl(AVIOCTRLDEFs.TCI_CMD_GET_MICROPHONE_REQ, new byte[1]);
            }

            if (deviceFeature.supportMicrophoneTune){
                getMicLevel();
            }
        }else{
            findViewById(R.id.ll_mic_volume_seekbar).setVisibility(View.GONE);
            showMicSeekBar(false);
        }
    }

    private void showMicSeekBar(boolean show){
        findViewById(R.id.ll_tv_progress).setVisibility(show? View.VISIBLE : View.GONE);
        findViewById(R.id.rl_mic_volume_seekbar).setVisibility(show? View.VISIBLE : View.GONE);
        String text = ResourcesUtil.getString(R.string.microphone);
        int progress =  adjustProgress(info.micVolume);
        mMicVolumeSeekbar.setProgress(progress);
        if (show){
            progress = progress / 10;
            text = text + " " + progress;
            mMicrophoneRL.setText(text);
        }

        mMicrophoneRL.setText(text);
    }

    private void initData() {
        info = getIntent().getParcelableExtra(DeviceSettingsActivity.EXT_DEVICE_INFO);
        camera = info == null? null : CameraHub.getInstance().getCamera(info.uuid);
        deviceFeature = DeviceFeatureObjectBox.queryDeviceFeature(info.uuid);
        deviceItem = getIntent().getParcelableExtra(CommonConstants.EXT_DEVICE_ITEM);
        if (camera!=null){
            camera.registerICameraListener(this);
            if (!camera.isConnected()){
                camera.connect();
            }
        }
    }

    public static int adjustProgress(int progress){
        if (progress % 10 != 0){
            progress = (progress / 10) * 10;
        }
        return progress;
    }
    @Override
    protected void initView() {
        mVolumeSeekbar = findViewById(R.id.speaker_volume_seekbar);
        mMicVolumeSeekbar = findViewById(R.id.mic_volume_seekbar);
        mMicrophoneRL = findViewById(R.id.rl_settings_device_microphone);
        mVolumeTextView = findViewById(R.id.tv_speaker_volume);
        mVolumeSeekbar.setOnRangeChangedListener(mVolumeRangeChangedListener);

        mMicrophoneRL.setOnClickListener(v -> {
            if (mMicrophoneRL.isChecked()) {
                setMicrophoneCMD(1);
            } else {
                setMicrophoneCMD(0);
            }

            showMicSeekBar(mMicrophoneRL.isChecked() && deviceFeature != null && deviceFeature.supportMicrophoneTune);

        });


        mMicVolumeSeekbar.setOnRangeChangedListener(mMicRangeChangedListener);
        backClickEvent();
    }

    private final OnRangeChangedListener mMicRangeChangedListener = new OnRangeChangedListener() {
        @Override
        public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
            TGLog.d(TAG, "isFromUser:" + isFromUser +  ",leftValue = " + leftValue + ", right = " + rightValue + ", seekbar-left = " + view.getLeftSeekBar().getProgress());
            if (isFromUser){
                if (leftValue < 1){
                    leftValue = 1;
                }
                int progress = adjustProgress((int)leftValue) / 10;
                mMicrophoneRL.setText(ResourcesUtil.getString(R.string.microphone) + " " + progress);
            }
        }
        @Override
        public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {}

        @Override
        public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {
            TGLog.d("isLeft = "+isLeft);
            if (isLeft){
                int progress = (int)view.getLeftSeekBar().getProgress();
                progress = adjustProgress(progress);
                TGLog.d(TAG, "val = " + progress);
                setMicLevel(progress);
            }
        }

        @Override
        public float onModifyProgress(float progress) {
            return 0;
        }
    };

    private final OnRangeChangedListener mVolumeRangeChangedListener = new OnRangeChangedListener() {
        @Override
        public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
            TGLog.d(TAG, "isFromUser:" + isFromUser +  ",leftValue = " + leftValue + ", right = " + rightValue + ", seekbar-left = " + view.getLeftSeekBar().getProgress());
            if (isFromUser){
                if (leftValue < 1){
                    leftValue = 1;
                }
                int progress = adjustProgress((int)leftValue) / 10;
                String text = ResourcesUtil.getString(R.string.speaker) + " " + progress;
                mVolumeTextView.setText(text);
            }
        }
        @Override
        public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {}

        @Override
        public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {
            TGLog.d("isLeft = "+isLeft);
            if (isLeft){
                int progress = (int)view.getLeftSeekBar().getProgress();
                progress = adjustProgress(progress);
                if (info != null && progress != info.speakerVolume){
                    setSpeakerVolume(progress);
                }
            }
        }

        @Override
        public float onModifyProgress(float progress) {
            return 0;
        }
    };

    private void setMicrophoneCMD(int on) {
        if (camera != null) {
            camera.setMicrophoneCMD(on);
        }
    }

    private void setMicLevel(int progress){
        if (camera != null) {
            camera.sendIOCtrl(TCI_CMD_SET_MIC_LEVEL_REQ, SpeakerVolumeHelper.parseMicLevelContent(progress));
        }
    }

    private void getMicLevel(){
        if (camera != null) {
            camera.sendIOCtrl(TCI_CMD_GET_MIC_LEVEL_REQ, new byte[1]);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (camera!=null){
            camera.registerICameraListener(this);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (camera!=null){
            camera.unregisterICameraListener(this);
        }
    }

    private void setSpeakerVolume(int volume){
        if (camera!=null){
            camera.sendIOCtrl(AVIOCTRLDEFs.TCI_CMD_SET_VOLUME_REQ,AVIOCTRLDEFs.Tcis_GetVolumeResp.parseContent(volume));
        }
    }

    @Override
    public void receiveUpdateConnectStates(int state) {

    }

    @Override
    public void receiveIOCtrlData(int type, byte[] data) {
        if (type== AVIOCTRLDEFs.TCI_CMD_SET_COMMAND_RESP){
            int command = Packet.byteArrayToInt_Little(data, 0);
            int result = Packet.byteArrayToInt_Little(data, 4);
            if (result == 0) {
                completeSend();
            }

            DeviceSettingHelper.updateSettings(deviceFeature, info);
            if (command == AVIOCTRLDEFs.TCI_CMD_SET_MICROPHONE_REQ||command ==AVIOCTRLDEFs.TCI_CMD_SET_MICROPHONE_RESP) {
                if (result == 0) {
                    info.microphoneOn = mMicrophoneRL.isChecked() ? 1 : 0;
                    TGLog.d("CameraViewActivity",  "info.b11 = " + info.microphoneOn);
                    sendUpdateSettingBroadcast(info);
                }
            } else if (command == TCI_CMD_SET_MIC_LEVEL_REQ) {
                TGLog.d(TAG,  "TCI_CMD_SET_MIC_LEVEL_REQ result = " + result);
                if (result == 0){
                    int progress = (int)mMicVolumeSeekbar.getLeftSeekBar().getProgress();
                    info.micVolume = adjustProgress(progress);
                    sendUpdateSettingBroadcast(info);
                }

            } else if (command == AVIOCTRLDEFs.TCI_CMD_SET_VOLUME_REQ){
                TGLog.d(TAG,  "TCI_CMD_SET_VOLUME_REQ result = " + result);
                if (result == 0){
                    info.speakerVolume = (int)mVolumeSeekbar.getLeftSeekBar().getProgress();
                    info.speakerVolume = adjustProgress(info.speakerVolume);
                    sendUpdateSettingBroadcast(info);
                }
            }
        }else if (type == AVIOCTRLDEFs.TCI_CMD_GET_MICROPHONE_RESP) {
            byte b = Packet.byteArrayToByte_Little(data, 4);
            info.microphoneOn = b;
            mMicrophoneRL.setChecked(info.microphoneOn == DeviceStateConstants.DEVICE_OPEN);
            if (info.microphoneOn == DeviceStateConstants.DEVICE_OPEN){
                showMicSeekBar(deviceFeature != null && deviceFeature.supportMicrophoneTune);
            }else{
                showMicSeekBar(false);
            }
            TGLog.d(TAG,  "info.b1122 = " + info.microphoneOn);
            sendUpdateSettingBroadcast(info);
        } else if (type == TCI_CMD_GET_MIC_LEVEL_REQ + 1){
            final int progress = Packet.byteArrayToInt_Little(data, 0);
            info.micVolume = adjustProgress(progress);
            sendUpdateSettingBroadcast(info);
            TGThreadPool.executeOnUiThread(() -> {
                TGLog.d(TAG,  "progress = " + info.micVolume);
                mMicVolumeSeekbar.setOnRangeChangedListener(null);
                mMicVolumeSeekbar.setProgress(info.micVolume);
                mMicVolumeSeekbar.setOnRangeChangedListener(mMicRangeChangedListener);
                if (DeviceFeatureHelper.isSupportMicrophoneSetting(deviceFeature)) {
                    if (info.microphoneOn == DeviceStateConstants.DEVICE_OPEN){
                        showMicSeekBar(deviceFeature.supportMicrophoneTune);
                    }else{
                        showMicSeekBar(false);
                    }
                }
            });


        }  else if (type == AVIOCTRLDEFs.TCI_CMD_GET_VOLUME_RESP) {
            info.speakerVolume = Packet.byteArrayToInt_Little(data, 4);
            info.speakerVolume = adjustProgress(info.speakerVolume);
            sendUpdateSettingBroadcast(info);
            TGThreadPool.executeOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mVolumeSeekbar.setOnRangeChangedListener(null);
                    mVolumeSeekbar.setProgress(info.speakerVolume);
                    mVolumeSeekbar.setOnRangeChangedListener(mVolumeRangeChangedListener);
                    int progress = info.speakerVolume / 10;
                    String text = ResourcesUtil.getString(R.string.speaker) + " " + progress;
                    mVolumeTextView.setText(text);
                }
            });

        } else if (type == AVIOCTRLDEFs.TCI_CMD_SET_MICROPHONE_RESP) {
            int result = Packet.byteArrayToInt_Little(data, 0);
            if (result == 0) {
                info.microphoneOn = mMicrophoneRL.isChecked() ? 1 : 0;
                TGLog.d("CameraViewActivity",  "info.b11 = " + info.microphoneOn);
                sendUpdateSettingBroadcast(info);

            }
        }else if (type == TCI_CMD_SET_MIC_LEVEL_REQ + 1) {
            int result = Packet.byteArrayToInt_Little(data, 0);
            TGLog.d(TAG,  "TCI_CMD_SET_MIC_LEVEL_REQ result = " + result);
            if (result == 0){
                int progress = (int)mMicVolumeSeekbar.getLeftSeekBar().getProgress();
                info.micVolume = adjustProgress(progress);
                sendUpdateSettingBroadcast(info);
            }

        }
    }
}